package com.teamsun.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;
import com.teamsun.annotation.PrivateHandlerMethod;
import com.teamsun.cache.CacheManager;
import com.teamsun.entity.AccessIn;
import com.teamsun.entity.DBCfg;
import com.teamsun.rptcfg.BaseRpt;
import com.teamsun.service.IRptMgrService;
import com.teamsun.service.ISequenceService;
import com.teamsun.util.Base64Util;
import com.teamsun.util.Constants;
import com.teamsun.util.RptToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报表接入系统管理
 */
@Controller
@RequestMapping("/rptTools/accessIn")
public class AccessInSysController {

    @Autowired
    private IRptMgrService rptMgrService;

    @Autowired
    private ISequenceService sequenceService;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 接入系统管理页面跳转
     * @return
     */
    @RequestMapping("/accessInSys")
    @PrivateHandlerMethod
    public String accessIn() {
        return "../WEB-INF/page/accessInSys";
    }

    /**
     * 分页查询接入系统信息
     */
    @RequestMapping("/queryAccessInSys")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject queryAccessInSys(HttpServletRequest request, int page, int rows) {
        JSONObject jsonObject = new JSONObject();

        int startIndex = (page - 1) * rows + 1;
        int endIndex = page * rows;

        Map<String, Object> param = new HashMap<String, Object>();
        String sysName = request.getParameter("sysName");  // 系统名称
        if(StringUtils.isNotBlank(sysName)) {
            sysName = sysName.trim();
            param.put("sysName", sysName);
        }

        Map<String, Object> resultMap = rptMgrService.queryAccessInByPage(param, startIndex, endIndex);

        jsonObject.put("rows", resultMap.get("rows"));
        jsonObject.put("total", resultMap.get("total"));
        return jsonObject;
    }

    /**
     * 删除接入系统
     */
    @RequestMapping("/deleteAccessIn")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject deleteAccessIn(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();

        try {
            String sid = request.getParameter("sid");  // sid
            String sysCode = request.getParameter("sysCode");  // 报表接入系统名称

            // 查询接入系统是否被报表使用，如果有报表使用该接入系统则不能删除
            List<Map<String, Object>> rptInfos = rptMgrService.queryRptByAccessIn(sysCode);
            if(rptInfos != null && rptInfos.size() > 0) {
                jsonObject.put("status", "0");
                jsonObject.put("errorMsg", "该系统正在被报表使用,无法删除");
            } else {
                // 删除报表接入系统
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("sid", sid);
                rptMgrService.deleteAccessIn(param);

                jsonObject.put("status", "1");
            }
        } catch (Exception e) {
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", "删除报表接入系统失败");
            e.printStackTrace();
        }

        return jsonObject;
    }

    /**
     * 保存接入系统信息
     */
    @RequestMapping("/addAccessIn")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject addAccessIn(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String sysName = request.getParameter("sysName");  // 系统名称
            sysName = sysName.trim();
            String sysCode = request.getParameter("sysCode");  // 系统代码
            sysCode = sysCode.trim();

            // 获取ID
            int sid = sequenceService.getRptSequence();

            // 查看系统代码是否重复
            List<AccessIn> accessIns = rptMgrService.queryAccessInByCode(sysCode);
            if(accessIns != null && accessIns.size() > 0) {
                jsonObject.put("status", "0");
                jsonObject.put("errorMsg", "系统代码[" + sysCode + "]已经存在");
            } else {
                // 将报表报表接入系统信息保存至数据库
                AccessIn accessIn = new AccessIn();
                accessIn.setSid(sid);
                accessIn.setSysCode(sysCode);
                accessIn.setSysName(sysName);
                rptMgrService.addAccessIn(accessIn);

                jsonObject.put("status", "1");
            }
        } catch (Exception e) {
            errroMsg = "新增报表接入系统失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 修改接入系统信息
     * @param request
     * @return
     */
    @RequestMapping("/updateAccessIn")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject updateAccessIn(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String sysId = request.getParameter("sid");
            String sysName = request.getParameter("sysName");  // 系统名称
            sysName = sysName.trim();
            String sysCode = request.getParameter("sysCode");  // 系统代码
            sysCode = sysCode.trim();

            boolean updateRpt = false;
            String oldCode = "";
            // 查看系统代码是否重复
            List<AccessIn> accessIns = rptMgrService.queryAccessInById(sysId);
            if(accessIns != null && accessIns.size() > 0) {
                AccessIn accessIn = accessIns.get(0);
                String sid = String.valueOf(accessIn.getSid());
                if(!sid.equals(sysId)) {
                    jsonObject.put("status", "0");
                    jsonObject.put("errorMsg", "系统代码[" + sysCode + "]已经存在");
                    return jsonObject;
                } else {
                    // 判断系统代码是否修改
                    oldCode = accessIn.getSysCode();
                    if(!oldCode.equals(sysCode)) {
                        updateRpt = true;
                    }
                }
            }

            // 将报表接入系统信息保存至数据库
            AccessIn accessIn = new AccessIn();
            accessIn.setSid(Integer.valueOf(sysId));
            accessIn.setSysCode(sysCode);
            accessIn.setSysName(sysName);
            rptMgrService.updateAccessIn(accessIn, updateRpt, oldCode);

            // 如果修改了接入系统的代码，则需要同步更新报表缓存信息
            if(updateRpt) {
                // 查询报表接入系统的报表信息，以便更新缓存
                List<Map<String, Object>> rptInfos = rptMgrService.queryRptByAccessIn(oldCode);
                if(!CollectionUtils.isEmpty(rptInfos)) {
                    for(Map<String, Object> map : rptInfos) {
                        String rptId = ((BigDecimal) map.get("rptId")).toString();
                        BaseRpt baseRpt = (BaseRpt) cacheManager.getRptCache(rptId);
                        baseRpt.setAccessSysCode(sysCode);
                        cacheManager.addRptCache(rptId, baseRpt);
                    }
                }
            }
            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "修改报表接入系统失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 设置接入系统Token
     * @param request
     * @return
     */
    @RequestMapping("/setSysToken")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject setSysToken(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String sysId = request.getParameter("sid");
            String sysCode = request.getParameter("sysCode");  // 系统代码

            // 查看是否已经设置Token,如果已经设置则无需重复设置
            List<AccessIn> accessIns = rptMgrService.queryAccessInById(sysId);
            if(accessIns != null && accessIns.size() > 0) {
                AccessIn accessIn = accessIns.get(0);
                String token = accessIn.getSysToken();
                if(StringUtils.isNotBlank(token)) {
                    jsonObject.put("status", "1");
                    return jsonObject;
                }
            }

            Map<String, Object> params = new HashMap<String, Object>();
            // 生成Token
            String sysToken = Base64Util.base64encode(sysCode + Constants.RPT_SALT);
            params.put("sysToken", sysToken);
            params.put("sysCode", sysCode);
            params.put("sid", sysId);

            // 修改接入系统的Token
            rptMgrService.updateSysToken(params);

            // 更新报表缓存中的token信息
            List<Map<String, Object>> rptInfos = rptMgrService.queryRptByAccessIn(sysCode);
            if(!CollectionUtils.isEmpty(rptInfos)) {
                for(Map<String, Object> map : rptInfos) {
                    String rptId = ((BigDecimal) map.get("rptId")).toString();
                    BaseRpt baseRpt = (BaseRpt) cacheManager.getRptCache(rptId);
                    baseRpt.setRptToken(sysToken);
                    cacheManager.addRptCache(rptId, baseRpt);
                }
            }

            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "设置系统Token失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 清空系统token
     * @param request
     * @return
     */
    @RequestMapping("/clearSysToken")
    @ResponseBody
    @PrivateHandlerMethod
    public JSONObject clearSysToken(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String errroMsg = "";
        try {
            String sysId = request.getParameter("sid");
            String sysCode = request.getParameter("sysCode");  // 系统代码

            // 查看系统Token为空,如果为空则无需重复置空
            List<AccessIn> accessIns = rptMgrService.queryAccessInById(sysId);
            if(accessIns != null && accessIns.size() > 0) {
                AccessIn accessIn = accessIns.get(0);
                String token = accessIn.getSysToken();
                if(StringUtils.isBlank(token)) {
                    jsonObject.put("status", "1");
                    return jsonObject;
                }
            }

            Map<String, Object> params = new HashMap<String, Object>();
            // 置空Token
            params.put("sysToken", "");
            params.put("sysCode", sysCode);
            params.put("sid", sysId);

            // 修改接入系统的Token
            rptMgrService.updateSysToken(params);

            // 更新报表缓存
            List<Map<String, Object>> rptInfos = rptMgrService.queryRptByAccessIn(sysCode);
            if(!CollectionUtils.isEmpty(rptInfos)) {
                for(Map<String, Object> map : rptInfos) {
                    String rptId = ((BigDecimal) map.get("rptId")).toString();
                    BaseRpt baseRpt = (BaseRpt) cacheManager.getRptCache(rptId);
                    baseRpt.setRptToken("");
                    cacheManager.addRptCache(rptId, baseRpt);
                }
            }

            jsonObject.put("status", "1");
        } catch (Exception e) {
            errroMsg = "置空系统Token失败";
            jsonObject.put("status", "0");
            jsonObject.put("errorMsg", errroMsg);
            e.printStackTrace();
        }
        return jsonObject;
    }
}
